package com.lyc.mall.service.impl;

import com.lyc.mall.dao.GoodsDao;
import com.lyc.mall.model.BO.AddGoodsBO;
import com.lyc.mall.model.BO.AddGoodsSpecBO;
import com.lyc.mall.model.PO.Goods;
import com.lyc.mall.model.PO.Spec;
import com.lyc.mall.model.PO.Type;
import com.lyc.mall.model.VO.GetGoodsByTypeVO;
import com.lyc.mall.service.GoodsService;
import com.lyc.mall.util.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.ArrayList;
import java.util.List;

public class GoodsServiceImpl implements GoodsService {
    @Override
    public List<Type> getType() {
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        GoodsDao goodsDao = sqlSession.getMapper(GoodsDao.class);
        List<Type> typeList = goodsDao.queryTypes();
        sqlSession.commit();
        sqlSession.close();
        return typeList;
    }

    @Override
    public List<GetGoodsByTypeVO> getGoodsByType(String typeId) {
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        GoodsDao goodsDao = sqlSession.getMapper(GoodsDao.class);
        List<GetGoodsByTypeVO> getGoodsByTypeVOList = goodsDao.queryTypeById(typeId);
        sqlSession.commit();
        sqlSession.close();
        return getGoodsByTypeVOList;
    }

    @Override
    public void addGoods(AddGoodsBO addGoodsBO) {
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        GoodsDao goodsDao = sqlSession.getMapper(GoodsDao.class);
        // goods需要的两个参数price和stock在BO中没有，需要在specList中运算得到
        List<AddGoodsSpecBO> addGoodsBOSpecList = addGoodsBO.getSpecList();
        Double unitPrice = addGoodsBOSpecList.get(0).getUnitPrice();
        Integer stockNum = addGoodsBOSpecList.get(0).getStockNum();
        for (int i = 1; i < addGoodsBOSpecList.size(); i++) {
            // 获取最小价格price
            if (addGoodsBOSpecList.get(i).getUnitPrice() < unitPrice) {
                unitPrice = addGoodsBOSpecList.get(i).getUnitPrice();
            }
            stockNum += addGoodsBOSpecList.get(i).getStockNum();
        }
        Goods goods = new Goods(null, addGoodsBO.getName(), Integer.parseInt(addGoodsBO.getTypeId()), addGoodsBO.getImg(),
                addGoodsBO.getDesc(), unitPrice, stockNum);
        try {
            goodsDao.insertGoods(goods);
            // todo 查询相应的goodsId
            int goodsId = goods.getId();
            // 还需要往规格表中新增数据
            List<Spec> specList = new ArrayList<>();
            for (AddGoodsSpecBO addGoodsSpecBO : addGoodsBOSpecList) {
                specList.add(new Spec(null, addGoodsSpecBO.getSpecName(), addGoodsSpecBO.getStockNum(), addGoodsSpecBO.getUnitPrice(), goodsId));
            }
            goodsDao.insertSpecList(specList);
        } catch (Exception e) {
            sqlSession.rollback();
            return;
        }
        sqlSession.commit();
        sqlSession.close();
    }
}
